package com.procurement.bidding.service.impl;

import com.procurement.bidding.domain.PcmBiddingMiddle;
import com.procurement.bidding.domain.PcmExpertSupplier;
import com.procurement.bidding.mapper.*;
import com.procurement.bidding.service.PcmBiddingMiddleService;
import com.procurement.bidding.utils.GetUser;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteJobService;
import com.ruoyi.system.api.RenotePcmService;
import com.ruoyi.system.api.domain.PcmAudit;
import com.ruoyi.system.api.domain.SysJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PcmBiddingMiddleServiceImpl implements PcmBiddingMiddleService {
    @Resource
    private PcmBiddingInviteTendersMapper pbitm;//创建项目
    @Resource
    private PcmBiddingMiddleMapper pbmm;//插入中间关联项目数据
    @Resource
    private PcmInvitedSupplierMapper pism;//邀标供应商表添加参加邀标的供应商
    @Resource
    private PcmExpertSupplierMapper pesm;
    @Resource
    private PcmExpertEvaluationProcessMapper peepm;//添加专家评标表数据
    @Resource
    private PcmPublicAttachmentMapper ppam;//上传文件
    @Resource
    private RenotePcmService rps;
    @Resource
    private RemoteJobService rjs;
    @Resource
    private PcmAuditMapper pam;
    @Resource
    private PcmEvaluationRuleDetailMapper perdm;

    @Override
    @Transactional
    public Integer addBiddingMiddle(Map<String, Object> map) {
        chuLi(map);
        map.put("projectNumber",rps.scbm("YB", SecurityConstants.INNER));
        map.put("projectCreator", GetUser.getLoggedInUserId());
        map.put("submissionTime",new Date());
        map.put("updateTime", new Date());
        System.out.println("map："+map);
        //新增项目
        Integer inviteTenders = pbitm.addBiddingInviteTenders(map);
//        //插入中间关联项目数据
        Integer middleNum = pbmm.addBiddingMiddle(map);
        /*添加邀标审核待办(如果可以多人邀标审核setSupplierid(1L)中的数据需要从数据库查询出来循环添加审核
         当一个人审核后修改所有setAuditTableNumber项目Id相同的字段的待办状态)*/
        PcmAudit pcmAudit = new PcmAudit();
        pcmAudit.setAuditTableName("邀标");
        pcmAudit.setAuditTableNumber(map.get("middleId").toString());
        pcmAudit.setAuditTableYwName("pcm_bidding_middle");
        pcmAudit.setAuditQuoteDeadline(new Date());
        pcmAudit.setSupplierid(1L);
        pam.addToExamine(pcmAudit);

//        //邀标供应商表添加参加邀标的供应商
        Integer invitedSuppliers = pism.addInvitedSupplier(map);
        Integer expertEvaluationProcess = 0;
        //添加专家评标表数据
        List<Map<String,Object>> expertList = (List<Map<String, Object>>) map.get("expertList");
        for (Map<String, Object> expert : expertList) {
            expert.put("middleId",map.get("middleId"));
            expertEvaluationProcess += peepm.addExpertEvaluationProcess(expert);
        }
//        //自增的专家评标ID
//        List<Integer> expertScoreIds = expertList.stream()
//                .map(item -> Integer.valueOf(item.get("expertScoreId").toString()))
//                .collect(Collectors.toList());
//        List<Integer> gysList = (List<Integer>) map.get("gysList");
//        for (Integer gys : gysList) {
//            pesm.addExpertSupplier(expertScoreIds,gys,Long.valueOf(map.get("middleId").toString()));
//        }


        List<Map<String,Object>> fileList = (List<Map<String, Object>>) map.get("fileList");
        if (fileList!=null&&fileList.size()>0){
            ppam.addInviteTenders(map);
        }

        return invitedSuppliers+middleNum+expertEvaluationProcess+inviteTenders;
    }


    @Override
    public List<PcmBiddingMiddle> showAllByMiddleNumberName(Map<String, Object> map) {
        return pbmm.showAllByMiddleNumberName(map);
    }

    @Override
    public PcmBiddingMiddle showAllByMiddleMainById(Long middleId) {
        return pbmm.showAllByMiddleMainById(middleId);
    }

    @Override
    @Transactional
    public Integer bidInvitationReviewPassed(Map<String, Object> map) {
        //projectInviteId 招标项目Id
//        chuLi(map);
        System.out.println("map："+map);
        //完成待办
        Integer updateState = pam.updateState(Long.valueOf(map.get("auditId").toString()));
        //修改项目状态
        map.put("reviewer", SecurityUtils.getUserId());
        map.put("reviewPassTime",new Date());
        Integer updateBiddingInviteTenders = pbitm.updateBiddingInviteTenders(map);

        Integer applicationGys = applicationGys(map);
        Long middleId = Long.valueOf(map.get("middleId").toString());
        Long projectInviteId = Long.valueOf(map.get("projectInviteId").toString());
        //报名截至时间定时任务  registrationDeadline  状态projectStatus：5
        addTaskDingTime("待转投标",projectInviteId,5,middleId,map.get("registrationDeadline").toString());
        addTaskDingTime("可投标",projectInviteId,2,middleId,map.get("biddingStartTime").toString());
        addTaskDingTime("转评标",projectInviteId,3,middleId,map.get("biddingEndTime").toString());
        addTaskDingTime("待转开标",projectInviteId,6,middleId,map.get("evaluationDeadline").toString());
        addTaskDingTime("流转完成",projectInviteId,4,middleId,map.get("plannedBidOpeningTime").toString());
        return updateState+updateBiddingInviteTenders+applicationGys;
    }
    private void addTaskDingTime(String jobName,Long projectInviteId,Integer projectStatus,Long middleId,String dateShi){
        SysJob sysJob = new SysJob();
        sysJob.setJobName(jobName);
        sysJob.setJobGroup("DEFAULT");
        StringBuilder str = new StringBuilder();
        str.append("ryTask.updateProjectStatus(");
        str.append(projectInviteId+",");
        str.append(projectStatus+",");
        str.append(middleId+")");
        sysJob.setInvokeTarget(str.toString());
        sysJob.setCronExpression("0/1 * * * * ?");
        sysJob.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        sysJob.setCreateTime(new Date());
        sysJob.setDelayInSeconds(dateShi);
        Long jobId = rjs.addTask(sysJob, SecurityConstants.INNER);
        sysJob.setJobId(jobId);
        rjs.runStartAt(sysJob,SecurityConstants.INNER);
    }

    @Override
    public PcmBiddingMiddle selApplicationGys(Long middleId) {
        return pbmm.selApplicationGys(middleId);
    }

    @Override
    @Transactional
    public Integer isApplicationGys(Map<String, Object> map) {
        System.out.println("map："+map);
        map.put("agreedInviter",SecurityUtils.getUserId());
        map.put("agreedInvitationTime",new Date());
        Integer usNum = pam.updateState(Long.valueOf(map.get("auditId").toString()));
        Long middleId = Long.valueOf(map.get("middleId").toString());
        Integer uaiNum = pism.updateAgreedInvitation(map);
        if (map.get("isAgreedInvitation").toString().equals("0")){
            List<Long> longs = peepm.selByMiddleId(middleId);
            longs.forEach(e->{
                map.put("expertScoreId",e);
                perdm.addRuleDetailMapper(map);
            });
            Long supplierId = Long.valueOf(map.get("supplierid").toString());
            List<Long> expertScoreIdList = peepm.selByMiddleId(middleId);
            pesm.addExpertSupplier(expertScoreIdList,supplierId,middleId);
        }
        return usNum+uaiNum;
    }

    @Override
    public List<Map<String, Object>> selByUserId(Map<String,Object> map) {
        map.put("userId",SecurityUtils.getUserId());
        return pbmm.selByUserId(map);
    }

    @Override
    public PcmBiddingMiddle selByMiddleIdTouBio(Long middleId) {
        PcmBiddingMiddle pbm = pbmm.selByMiddleIdTouBio(middleId);
        Long supplierId = pbmm.findBySupplierId(SecurityUtils.getUserId());
        Long expertScoreId = pesm.selBySupplierIdMiddleId(supplierId,middleId);
        pbm.setPcmEvaluationRuleDetailList(pbmm.selRuleDetailList(middleId,supplierId,expertScoreId));
        return pbm;
    }

    @Override
    public PcmBiddingMiddle selByMiddleIdExpert(Map<String, Object> map) {
        Long middleId = Long.valueOf(map.get("middleId").toString());
        Long supplierId = Long.valueOf(map.get("supplierId").toString());
        PcmBiddingMiddle pbm = pbmm.selByMiddleIdTouBio(middleId);
        pbm.setPcmPublicAttachmentList(pbmm.selAttachmentList(pism.selByMiddleIdSupplierId(middleId,supplierId)));
        pbm.setPcmEvaluationRuleDetailList(pbmm.selRuleDetailList(middleId,supplierId,peepm.selByExperIdMiddleId(SecurityUtils.getUserId(),middleId)));
        return pbm;
    }

    @Override
    public List<Map<String, Object>> selOpening(Map<String,Object> map) {
        return pbmm.selOpening(map);
    }

    private Integer applicationGys(Map<String,Object> map){
        List<Integer> pcmSupplierList = (List<Integer>) map.get("pcmSupplierList");
        Long middleId = Long.valueOf(map.get("middleId").toString());
        for (Integer supplierId : pcmSupplierList) {
            PcmAudit pcmAudit = new PcmAudit();
            pcmAudit.setAuditTableName("报名");
            pcmAudit.setAuditTableNumber(pism.selByMiddleIdSupplierId(middleId,supplierId.longValue()).toString());
            pcmAudit.setAuditTableYwName("pcm_invited_supplier");
            pcmAudit.setAuditQuoteDeadline(new Date());
            pcmAudit.setSupplierid(supplierId.longValue());
            pam.addToExamine(pcmAudit);
        }
        return 1;
    }

    private static void chuLi(Map<String,Object> map){
        // 对日期时间字段进行处理
        //报名截止时间
        String registrationDeadline = formatDate((String) map.get("registrationDeadline"));
        //投标开始时间
        String biddingStartTime = formatDate((String) map.get("biddingStartTime"));
        //投标结束时间
        String biddingEndTime = formatDate((String) map.get("biddingEndTime"));
        //评标截止时间
        String evaluationDeadline = formatDate((String) map.get("evaluationDeadline"));
        //计划开标时间
        String plannedBidOpeningTime = formatDate((String) map.get("plannedBidOpeningTime"));

        // 将处理后的日期时间字段重新放入 Map 中
        map.put("registrationDeadline", registrationDeadline);
        map.put("biddingStartTime", biddingStartTime);
        map.put("biddingEndTime", biddingEndTime);
        map.put("evaluationDeadline", evaluationDeadline);
        map.put("plannedBidOpeningTime", plannedBidOpeningTime);

    }

    private static String formatDate(String dateTime) {
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTime, DateTimeFormatter.ISO_DATE_TIME);
        ZonedDateTime localDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai"));
        return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }


}
